package com.huluobo.a2204kotlinjetpackdemo.lifecycle

import android.os.CountDownTimer
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

/**
 *  Created by LC on 2024/8/14.
 *  LifeCycle总结
 *  观察者模式三要素,观察者(Observer),被观察者(Observable),订阅关系(subscribe)
 *  1.如果要是用LifeCycle,首先要实现一个LifecycleObserver ,让他可以感知(观察)宿主的生命周期变化
 *  2.需要一个宿主,LifecycleOwner 由于AppCompatActivity已经通过继承关系实现了宿主接口,所以可以省略
 *  3.通过lifecycle.addObserver(adManager) ,来实现订阅关系
 *  4.可以有效解决宿主对象中空气其他控件的生命周期,让观察者可以跟随宿主的生命周期做出自行的判断,来调用某些方法,比如跟随Activity来一起create
 *  5.不会造成内存泄漏
 */
class ADManager(adViewModel: ADViewModel) : LifecycleObserver {
    private val countDownTimer = object : CountDownTimer(adViewModel.timing, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            Log.i("TagA", "广告剩余时间:${(millisUntilFinished / 1000).toInt()}秒")
            adViewModel.setTimingResult(millisUntilFinished)
        }

        override fun onFinish() {
            Log.i("TagA", "广告结束,准备进入主页面")
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun start() {
        Log.i("TagA", "开始计时")
        countDownTimer.start()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun stop() {
        Log.i("TagA", "计时结束")
        countDownTimer.cancel()
    }
}